package it.omnisong.server.retrieval;

import it.omnisong.client.model.Link;
import it.omnisong.client.model.Song;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class AstraWebDataSource extends AbstractDataSource {

	public AstraWebDataSource() {
		this.setBaseUrl("http://lyrics.astraweb.com");
		this.setxPathAlbumQuery("/html/body/table[3]/tbody/tr/td[3]/table/tbody/tr/td/table/tbody/tr[2]/td[2]/b");
		this.setxPathAuthorQuery("/html/body/table[3]/tbody/tr/td[3]/table/tbody/tr/td/table/tbody/tr[1]/td[2]/b");
		this.setxPathLyricQuery("/html/body/table[3]/tbody/tr/td[3]/font");
		this.setxPathTitleQuery("/html/body/table[3]/tbody/tr/td[3]/table/tbody/tr/td/table/tbody/tr[3]/td[2]/b");
	}


	@SuppressWarnings("unchecked")
	public List<Link> collectLinksByLetter() {
		List<Link> links 	 = new ArrayList<Link>();
		WebClient webClient  = this.getWebClient();
		String currentArtist = "";
		HtmlPage page = null;

		try {
			page = webClient.getPage(this.getBaseUrl()
					+ "/browse/A.html");
			/* Prende tutti gli artisti */
			List<HtmlElement> elements = (List<HtmlElement>) page.getByXPath(
					"/html/body/table[3]/tbody/tr/td/table/tbody/tr/td[2]/table/tbody//tr/td//a"
			);
	
			for (HtmlElement element: elements) {
				currentArtist		= element.asText();
				HtmlPage artistPage = element.click();
				/* Prende tutte le canzoni */
				List<HtmlElement> songElements = (List<HtmlElement>) artistPage.getByXPath(
					"/html/body/table[3]/tbody/tr/td/table/tbody/tr//blockquote/a"	
				);
				
				for (HtmlElement songElement: songElements) {
					Song song = new Song();
					Link link = new Link();
					
					song.setTitle(songElement.asText());
					song.setArtist(currentArtist);
					link.setUrl(songElement.getAttribute("href"));
					link.setSong(song);
					links.add(link);
					
					System.out.println("ASTRAWEB collecting: " + song.getTitle() + " - " + song.getArtist() + " - " + link.getUrl());
				}
			}
		} catch (FailingHttpStatusCodeException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return links;
	}

}
